import ApiService from './api';
import { ChatMessage, ChatSession, PaginationParams, PaginatedResponse } from '../types';
import { io, Socket } from 'socket.io-client';

// 聊天查询参数
export interface ChatQueryParams extends PaginationParams {
  shopId?: string;
  customerId?: string;
  serviceId?: string;
  status?: 'waiting' | 'active' | 'closed';
  keyword?: string;
}

// 发送消息数据
export interface SendMessageData {
  sessionId: string;
  content: string;
  messageType: 'text' | 'image' | 'file';
}

// WebSocket事件类型
export interface ChatEvents {
  'new-message': (message: ChatMessage) => void;
  'session-updated': (session: ChatSession) => void;
  'user-typing': (data: { sessionId: string; userId: string; isTyping: boolean }) => void;
  'user-online': (data: { userId: string; isOnline: boolean }) => void;
}

// 客服聊天服务
export class ChatService {
  private static socket: Socket | null = null;
  private static eventListeners: Map<string, Function[]> = new Map();
  
  // 初始化WebSocket连接
  static initSocket(): Socket {
    if (!this.socket) {
      const token = localStorage.getItem('admin_token');
      const socketUrl = import.meta.env.VITE_SOCKET_URL || 'http://localhost:3002';
      
      this.socket = io(socketUrl, {
        auth: {
          token,
        },
        transports: ['websocket'],
      });
      
      // 连接事件
      this.socket.on('connect', () => {
        console.log('Socket connected:', this.socket?.id);
      });
      
      this.socket.on('disconnect', () => {
        console.log('Socket disconnected');
      });
      
      this.socket.on('error', (error) => {
        console.error('Socket error:', error);
      });
      
      // 重新连接时重新认证
      this.socket.on('connect', () => {
        const currentToken = localStorage.getItem('admin_token');
        if (currentToken) {
          this.socket?.emit('authenticate', { token: currentToken });
        }
      });
    }
    
    return this.socket;
  }
  
  // 断开WebSocket连接
  static disconnectSocket(): void {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
      this.eventListeners.clear();
    }
  }
  
  // 监听事件
  static on<K extends keyof ChatEvents>(event: K, callback: ChatEvents[K]): void {
    const socket = this.initSocket();
    socket.on(event, callback);
    
    // 保存监听器引用以便后续清理
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, []);
    }
    this.eventListeners.get(event)?.push(callback);
  }
  
  // 移除事件监听
  static off<K extends keyof ChatEvents>(event: K, callback?: ChatEvents[K]): void {
    if (this.socket) {
      if (callback) {
        this.socket.off(event, callback);
      } else {
        this.socket.off(event);
      }
    }
    
    // 清理监听器引用
    if (callback) {
      const listeners = this.eventListeners.get(event);
      if (listeners) {
        const index = listeners.indexOf(callback);
        if (index > -1) {
          listeners.splice(index, 1);
        }
      }
    } else {
      this.eventListeners.delete(event);
    }
  }
  
  // 发送消息
  static sendMessage(data: SendMessageData): void {
    const socket = this.initSocket();
    socket.emit('send-message', data);
  }
  
  // 加入会话房间
  static joinSession(sessionId: string): void {
    const socket = this.initSocket();
    socket.emit('join-session', { sessionId });
  }
  
  // 离开会话房间
  static leaveSession(sessionId: string): void {
    const socket = this.initSocket();
    socket.emit('leave-session', { sessionId });
  }
  
  // 发送正在输入状态
  static sendTyping(sessionId: string, isTyping: boolean): void {
    const socket = this.initSocket();
    socket.emit('typing', { sessionId, isTyping });
  }
  
  // 标记消息为已读
  static markAsRead(sessionId: string, messageIds: string[]): void {
    const socket = this.initSocket();
    socket.emit('mark-read', { sessionId, messageIds });
  }
  
  // REST API 方法
  
  // 获取聊天会话列表
  static async getSessions(params: ChatQueryParams): Promise<PaginatedResponse<ChatSession>> {
    return await ApiService.get<PaginatedResponse<ChatSession>>('/admin/chat/sessions', params);
  }
  
  // 获取会话详情
  static async getSession(id: string): Promise<ChatSession> {
    return await ApiService.get<ChatSession>(`/admin/chat/sessions/${id}`);
  }
  
  // 获取会话消息
  static async getSessionMessages(sessionId: string, params: PaginationParams): Promise<PaginatedResponse<ChatMessage>> {
    return await ApiService.get<PaginatedResponse<ChatMessage>>(`/admin/chat/sessions/${sessionId}/messages`, params);
  }
  
  // 创建新会话
  static async createSession(data: {
    customerId: string;
    shopId: string;
    initialMessage?: string;
  }): Promise<ChatSession> {
    return await ApiService.post<ChatSession>('/admin/chat/sessions', data);
  }
  
  // 分配客服
  static async assignService(sessionId: string, serviceId: string): Promise<ChatSession> {
    return await ApiService.post<ChatSession>(`/admin/chat/sessions/${sessionId}/assign`, { serviceId });
  }
  
  // 转移会话
  static async transferSession(sessionId: string, newServiceId: string, reason?: string): Promise<ChatSession> {
    return await ApiService.post<ChatSession>(`/admin/chat/sessions/${sessionId}/transfer`, {
      newServiceId,
      reason,
    });
  }
  
  // 关闭会话
  static async closeSession(sessionId: string, reason?: string): Promise<ChatSession> {
    return await ApiService.post<ChatSession>(`/admin/chat/sessions/${sessionId}/close`, { reason });
  }
  
  // 重新打开会话
  static async reopenSession(sessionId: string): Promise<ChatSession> {
    return await ApiService.post<ChatSession>(`/admin/chat/sessions/${sessionId}/reopen`);
  }
  
  // 获取等待中的会话
  static async getWaitingSessions(params: PaginationParams): Promise<PaginatedResponse<ChatSession>> {
    return await ApiService.get<PaginatedResponse<ChatSession>>('/admin/chat/sessions/waiting', params);
  }
  
  // 获取我的会话（当前客服）
  static async getMySessions(params: PaginationParams): Promise<PaginatedResponse<ChatSession>> {
    return await ApiService.get<PaginatedResponse<ChatSession>>('/admin/chat/sessions/my', params);
  }
  
  // 发送文本消息（REST API）
  static async sendTextMessage(sessionId: string, content: string): Promise<ChatMessage> {
    return await ApiService.post<ChatMessage>('/admin/chat/messages', {
      sessionId,
      content,
      messageType: 'text',
    });
  }
  
  // 上传并发送图片消息
  static async sendImageMessage(sessionId: string, file: File): Promise<ChatMessage> {
    const uploadResult = await ApiService.upload('/admin/chat/upload/image', file);
    return await ApiService.post<ChatMessage>('/admin/chat/messages', {
      sessionId,
      content: uploadResult.url,
      messageType: 'image',
    });
  }
  
  // 上传并发送文件消息
  static async sendFileMessage(sessionId: string, file: File): Promise<ChatMessage> {
    const uploadResult = await ApiService.upload('/admin/chat/upload/file', file);
    return await ApiService.post<ChatMessage>('/admin/chat/messages', {
      sessionId,
      content: JSON.stringify({
        url: uploadResult.url,
        filename: file.name,
        size: file.size,
      }),
      messageType: 'file',
    });
  }
  
  // 获取聊天统计
  static async getChatStats(period: 'day' | 'week' | 'month' = 'month'): Promise<{
    totalSessions: number;
    activeSessions: number;
    closedSessions: number;
    averageResponseTime: number;
    customerSatisfaction: number;
    messageStats: Array<{
      date: string;
      messages: number;
      sessions: number;
    }>;
  }> {
    return await ApiService.get('/admin/chat/stats', { period });
  }
  
  // 获取客服工作量统计
  static async getServiceWorkload(serviceId?: string): Promise<Array<{
    serviceId: string;
    serviceName: string;
    activeSessions: number;
    totalSessions: number;
    averageResponseTime: number;
    customerRating: number;
  }>> {
    return await ApiService.get('/admin/chat/service-workload', { serviceId });
  }
  
  // 获取常用回复模板
  static async getQuickReplies(shopId?: string): Promise<Array<{
    id: string;
    title: string;
    content: string;
    category: string;
    usage: number;
  }>> {
    return await ApiService.get('/admin/chat/quick-replies', { shopId });
  }
  
  // 创建快速回复模板
  static async createQuickReply(data: {
    title: string;
    content: string;
    category: string;
    shopId?: string;
  }): Promise<any> {
    return await ApiService.post('/admin/chat/quick-replies', data);
  }
  
  // 更新快速回复模板
  static async updateQuickReply(id: string, data: {
    title?: string;
    content?: string;
    category?: string;
  }): Promise<any> {
    return await ApiService.put(`/admin/chat/quick-replies/${id}`, data);
  }
  
  // 删除快速回复模板
  static async deleteQuickReply(id: string): Promise<void> {
    await ApiService.delete(`/admin/chat/quick-replies/${id}`);
  }
  
  // 搜索历史消息
  static async searchMessages(params: {
    keyword: string;
    shopId?: string;
    customerId?: string;
    startDate?: string;
    endDate?: string;
    page?: number;
    limit?: number;
  }): Promise<PaginatedResponse<ChatMessage>> {
    return await ApiService.get<PaginatedResponse<ChatMessage>>('/admin/chat/messages/search', params);
  }
  
  // 导出聊天记录
  static async exportChatHistory(params: {
    sessionId?: string;
    shopId?: string;
    startDate?: string;
    endDate?: string;
  }): Promise<void> {
    await ApiService.download('/admin/chat/export', 'chat-history.xlsx');
  }
}

export default ChatService;
